﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;

namespace MyLib
{
    public class EmailUtil
    {
        public static bool SendMail(string to,string subject, string body)
        {
            return SendMail(to, "", subject, body);
        }

        /// <summary>
        ///  发邮件，需要配置config文件。
         ///<system.net>
          ///  <!--如果是第三方smtp服务器,需要指定userName 和 password,并根据host指定发件人邮件地址from
		 ///       测试发现from值必须是userName值加上指定的smpt服务器才行,而且是必须指定的
		 ///       如果是本机smtp服务器,只需指定defaultCredentials="true"即可10.0.0.252-->
          ///  <mailSettings>
          ///    <smtp deliveryMethod="Network" from="test@163.com">
          ///      <network host="smtp.163.com" port="25" userName="test@163.com" password="111111" defaultCredentials="false"/>
          ///    </smtp>
          ///  </mailSettings>
         /// </system.net>
        /// </summary>
        /// <param name="to"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <returns></returns>        
        public static bool SendMail(string to, string cc, string subject, string body)
        {
            if (string.IsNullOrEmpty(to))
            {
                return false;
            }
            using (MailMessage message = new MailMessage())
            {
                to = to.Replace(",", ";");
                cc = cc.Replace(",", ";");
                string[] strEmailSingle = to.Split(';');
                for (int k = 0; k < strEmailSingle.Length; k++)
                {
                    message.To.Add(new MailAddress(strEmailSingle[k].Trim())); //收件人邮箱
                }
                if (!string.IsNullOrEmpty(cc))
                {
                    strEmailSingle = cc.Split(';');
                    for (int k = 0; k < strEmailSingle.Length; k++)
                    {
                        message.CC.Add(new MailAddress(strEmailSingle[k].Trim())); //抄送人邮箱
                    }
                }
                message.Subject = subject;
                message.Body = body;
                message.IsBodyHtml = true;
                string from = ConfigurationManager.AppSettings["smtp.from"];
                string displayName = ConfigurationManager.AppSettings["smtp.displayName"];
                if (!string.IsNullOrEmpty(from))
                {
                    message.From = new MailAddress(from, displayName);
                }
                try
                {
                    SmtpClient mailClient = new SmtpClient();
                    mailClient.Send(message);
                }
                catch (Exception ex)
                {
                    string str = ex.Message;
                    Console.Write(str);
                    LogUtil.Error(ex);
                    return false;
                }
            }
            return true;
        }
    }
}
